<?php
use sinacloud\sae\Storage as Storage;
/**
 * Yjnic_Sae_Storage storage存储
 *
 * @package     Yjnic\Sae
 * @author      prettyyjnic <prettyyjnic@qq.com> 2015-11-22
 */

class Yjnic_Sae_Storage implements Yjnic_StorageInterface {
    private $_bucket = '';

    public function __construct($configs){
        if (empty($configs)) {
            throw new Yjnic_Sae_Exception("Default bucket can not be empty", 500);            
        }
        $this->_bucket = $configs['bucket'];
        Storage::setAuth(SAE_APPNAME.':'.SAE_ACCESSKEY, SAE_SECRETKEY);
        Storage::$useExceptions = TRUE;
    }

    public function bucket($bucket){
        $this->_bucket = $bucket;
        return $this;
    }

    //读取一个Object
    public function get($upload_name){
        $obj = Storage::getObject($this->_bucket, $upload_name);
        if ($obj['error']) {
            return false;  
        }
        return $obj['body'];
    }

    /**
     * @param $file, 要上传的文件的buffer或者路径
     * @param $upload_name , 保存的名字
     * @param $is_cover , 是否覆盖
     */
    public function upload($file, $upload_name, $is_cover=false){
        if ($is_cover==false && Storage::getObjectInfo($this->_bucket, $upload_name)) {//检查是否已经存在
            throw new Yjnic_Sae_Exception("Upload file is exists", 401); 
        }
        if (Storage::putObject(Storage::inputFile($file), $this->_bucket, $upload_name)) {
            return $upload_name;
        }else{
            throw new Yjnic_Sae_Exception("Upload file Error", 402);           
        }
    }   

    //删除
    public function delete($upload_name){
        return Storage::deleteObject($this->_bucket, $upload_name);
    }
}